package com.cyp.livelog.web;

import com.cyp.livelog.utils.DbUtils;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @date 2020/12/15 18:29
 * @description
 */
@WebServlet("/register")
public class RegisterAction extends HttpServlet {

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    req.getRequestDispatcher("/register.jsp").forward(req, resp);
  }

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    req.setCharacterEncoding("UTF-8");
    String username = req.getParameter("username");
    String password = req.getParameter("password");
    String nickname = req.getParameter("nickname");
    List<Object> params = new ArrayList();
    params.add(username);
    ResultSet res = DbUtils.query("select username from user where username=?", username);
    try {
      if (res.next()) {
        req.setAttribute("message", "账号已经存在");
        req.getRequestDispatcher("/register.jsp").forward(req, resp);
        return;
      }
    } catch (SQLException e) {
      e.printStackTrace();
    }
    DbUtils.update("insert into user(username,password,nickname,create_time) values(?,?,?,?)", username, password, nickname, new Date());
    req.setAttribute("message", username + "，注册成功！");
    req.getRequestDispatcher("/login.jsp").forward(req, resp);
  }
}
